<?php
class FileManagerList extends FormElement {
	protected $files = array( );
	protected $callback = null;

	public function __construct( $name, $label = '', array $files = array(), $callback = null ) {
		parent::__construct( $name, array( 'label' => $label ) );
		$this->files = $files;
		$this->callback = $callback;
	}

	public function __toString() {
		HeaderManager::addHeader(HeaderManager::X_JAVASCRIPT, 'Lib/FileManager/public/js/form_element.js');

		$html = '
		<div class="form filemanagerlist">
			<h2>' . $this->getProperty('label') . '</h2>';

		foreach( $this->files as $key => $file ) {
			if( $file->primary ) {
				$primary = $key;

				$html .= '
				<div class="filemanager primary">';
			} else {
				$html .= '
				<div class="filemanager">';
			}
			$html .= '
					<input type="hidden" name="'.$this->name.'[' . $key . ']" id="' . $this->name . '_' . $key . '" class="fileManagerInputField" value="' . $file->getFile( )->getFullPath( ) . '" />';

			if( $file->getFile( )->isImage( ) ) {
				$image = $file->getFile( );

				$html .= '
					<a href="' . $key . '" rel="' . $this->name . '_' . $key . '" class="browse">
						<img src="Lib/Images/Icons/delete.png" alt="##delete##" title="##delete##" />
					</a>
					<img src="' . $image->getImageResized(120,100) . '" alt="" class="thumb" />';
			} else {
				$html .= '
					<span id="' . $this->name . '_' . $key . '_span">' . $file->getFile( )->filename . '</span>
					<a href="#'.$this->callback.'" rel="' . $this->name . '_' . $key . '" class="filemanagerPopup">##browse##</a>';
			}

			$html .= ( $this->inAJAXMode() || !empty( $this->errorMessage ) ? '<div class="error' . ( $this->inAJAXMode() ? ' ajax' : '' ) . '" id="' . ( $this->getFormName() != '' ? $this->getFormName() . '_' : '' ) . $this->name . '_error">' . $this->errorMessage . '</div>' : '' );
			$html .= '
			</div>';
		}

		$key++;

		header( 'X-FileManagerList: ' . $key . ',' . $this->name );

		$html .= '
			<div class="filemanager addNew">
				<a href="#" id="linkAdd">
					<img src="Lib/Images/Icons/folder_add.png" alt="##add##" />
					##add##
				</a>
			</div>
			<script type="text/javascript">
				var newImageKey = ' . $key . ';
				var newImageName = "' . $this->name . '";
			</script>
			<input type="hidden" name="primaryInput" id="primaryInput" value="' . $primary . '" />
		</div>';

		return $html;
	}
}
?>